package model

import (
	"database/sql"
	"fmt"
	"github.com/DATA-DOG/go-txdb"
	"os"

	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/postgres" //postgres dependency

	"maki/config"
)

// DB 数据库连接
var DB *gorm.DB

// Models all models
var Models = []interface{}{
	&User{}, &Article{}, &Comment{}, &Tag{},
}

func initDB() {
	var db *gorm.DB
	var err error
	if config.ServerConfig.Env == config.ServerEnv.TestMode {
		txdb.Register("txdb", config.DBConfig.Dialect, config.DBConfig.URL)
		sqlDB, err := sql.Open("txdb", "roottxdb_test")
		if err != nil {
			panic(err)
		}
		db, err = gorm.Open(config.DBConfig.Dialect, sqlDB)
	} else {
		db, err = gorm.Open(config.DBConfig.Dialect, config.DBConfig.URL)
	}
	if err != nil {
		fmt.Println(err.Error())
		os.Exit(-1)
	}
	if config.ServerConfig.Env == config.ServerEnv.DevelopmentMode {
		db.LogMode(true)
	}
	db.AutoMigrate(Models...)
	db.DB().SetMaxIdleConns(config.DBConfig.MaxIdleConns)
	db.DB().SetMaxOpenConns(config.DBConfig.MaxOpenConns)
	DB = db.Set("gorm:association_autoupdate", false)
}

func init() {
	initDB()
}
